package com.example.anquan.controller;


import com.example.anquan.Service.ArticleService;
import com.example.anquan.Service.CommentService;
import com.example.anquan.guanli.Article;
import com.example.anquan.guanli.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * @author ASUS
 */
@Controller
public class ArticleController {
        @Autowired
        private ArticleService articleService;
        @Autowired
        private CommentService commentService;
        //访问主页时转到分页的第一页
        @GetMapping("/")
        public String index(Model model){
                return page(1, model);
        }
        //分页显示文章
        @GetMapping("/page/{page}")
        public String page(@PathVariable("page") int page, Model model){
                //分页每页文章数
                int size = 5;
                Page<Article> articles = articleService.pageArticle(page-1, size);
                model.addAttribute("page", page);
                model.addAttribute("totalPage", articles.getTotalPages());
                model.addAttribute("articles", articles.getContent());
                return "index";
        }
        //文章详情页
        //文章详情页
        @GetMapping("/article/{id}")
        public String article(@PathVariable("id") int id, Model model){
                Article article = articleService.findArticleById(id);
                List<Comment> comments = commentService.findCommentByArticleId(id);
                model.addAttribute("article", article);
                model.addAttribute("comments",comments);
                return "/article";
        }
        //发表评论
        @PostMapping("/article/{id}/comment")
        public String comment(@PathVariable("id") int id, @RequestParam("author")
                String author, @RequestParam("content")String content){
                commentService.addComment(id, author, content);
                return "redirect:/article/"+id;
        }
}
